//
//  ViewController.m
//  GCD-TimerDeom
//
//  Created by FelixYin on 2020/4/11.
//  Copyright © 2020 FelixYin. All rights reserved.
//

#import "ViewController.h"
#import "FYTimer.h"

/*
 NSTimer计时器依赖于RunLoop,当RunLoop任务繁重的时候，可能会导致NSTimer不准时，所以我们可以通过GCD创建一个计时器，让计时更加准确
 
 使用GCD创建计时器：
 
 */

@interface ViewController ()

@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,copy) NSString *timerID;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self addGCDTimer];
    
    [self addCustomTimer];
}

- (void) addCustomTimer{
    NSString *timerID = [FYTimer schedule:^(id  _Nonnull obj) {
        NSLog(@"执行任务 === %@",[NSThread currentThread]);
    } start:0 interval:1 repeat:YES async:YES];
    self.timerID = timerID;
}

- (void)cancleTimer{
    NSLog(@"取消定时器任务");
    [FYTimer cancleSchedule:self.timerID];
}

- (void) addGCDTimer{
    
    //定时器执行任务的队列，也可以使用其他队里执行定时器任务
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    //创建定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    //设置定时器开始时间及执行任务的频率
    uint64_t start = 2; //两秒后执行
    uint64_t interval = 1; //每1秒执行一次任务
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start*NSEC_PER_SEC), interval*NSEC_PER_SEC, 0);
    
    //设置定时器任务
//    dispatch_source_set_event_handler(timer, ^{
//        NSLog(@"=== GCD定时器任务");
//    });
    
    dispatch_source_set_event_handler_f(timer, timerFire);
    
    //启动定时器
    dispatch_resume(timer);
    
    NSLog(@"计时器开始");
    self.timer = timer;
    
}

void timerFire(void *param){
    NSLog(@"使用函数执行GCD定时器任务 == Thread == %@",[NSThread currentThread]);
}

@end
